package datamodels

import (
	"database/sql/driver"
	"encoding/json"
	"github.com/pkg/errors"
)

type Json map[string]interface{}

func (p Json) Value() (driver.Value, error) {
	if len(p) == 0 {
		return `{}`,nil
	}
	j, err := json.Marshal(p)
	return j, err
}

func (p *Json) Scan(src interface{}) error {
	source, ok := src.([]byte)
	if !ok {
		return errors.New("Type assertion .([]byte) failed.")
	}

	var i interface{}
	if err := json.Unmarshal(source, &i); err != nil {
		return err
	}

	*p, ok = i.(map[string]interface{})
	if !ok {
		return errors.New("Type assertion .(map[string]interface{}) failed.")
	}

	return nil
}

func (p Json)Merge(source Json) Json {
	target := p
	for key, value := range source {
		target[key] = value
	}
	return target
}

